package com.qdxwx.common.utils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 *
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
public class PropertyUtils {

	private static final Map<String, Properties> instance = Collections.synchronizedMap(new HashMap<>());

	public static Properties getInstance(String sourceUrl) {
		synchronized (PropertyUtils.class) {
			Properties source = instance.get(sourceUrl);
			if (source == null) {
				source = getProperties(sourceUrl);
				instance.put(sourceUrl, source);
			}
			return source;
		}
	}

	public static Properties getConfiguration(String sourceUrl) {
		return getInstance(sourceUrl);
	}

	public static void saveConfiguration(String propFileName, Map<String,String> props) {
		if (propFileName.lastIndexOf(".") < 0) {
			propFileName = propFileName + ".properties";
		}
		String propFile = PropertyUtils.class.getClassLoader().getResource(propFileName).getPath();
		Properties properties = getConfiguration(propFileName);
		try {
			FileOutputStream fileOutputStream = new FileOutputStream(propFile,false);
			for (Map.Entry<String, String> entry : props.entrySet()) {
				properties.setProperty(entry.getKey(), entry.getValue());
			}
			properties.store(fileOutputStream, "the properties are written by the program.");
			fileOutputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static synchronized Properties getProperties(String sourceUrl) {
		String filePath = sourceUrl;
		if (filePath.lastIndexOf(".") < 0) {
			filePath = filePath + ".properties";
		}
		InputStream configurationStream = PropertyUtils.class.getClassLoader().getResourceAsStream(filePath);//"generator.properties"
		try {
			Properties properties = new Properties();
			properties.load(configurationStream);
			return properties;
		} catch (IOException e) {
			throw new Error(e);
		} finally {
			if (configurationStream != null) try {
				configurationStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}